package course.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import course.pojo.entity.Admin;
import course.pojo.entity.College;
import course.pojo.vo.Page;
import course.service.CollegeService;
import course.service.impl.CollegeServiceImpl;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author HLF
 * @date 2022/7/1 10:05
 */
@WebServlet("/admin/collegeController")
public class CollegeController extends BaseController {

    private CollegeService collegeService = new CollegeServiceImpl();

    /**
     * 跳转到college_manage.jsp
     */
    protected void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageNo = req.getParameter("pageNo");
        this.main(req, resp, pageNo);
    }

    protected void main(HttpServletRequest req, HttpServletResponse resp, String pageNo) throws ServletException, IOException {
        if (pageNo == null || Integer.parseInt(pageNo) <= 0) {
            pageNo = "1";
        }

        Page<College> page = collegeService.page(Integer.valueOf(pageNo));

        req.setAttribute("page", page);
        req.getRequestDispatcher("/college_manage.jsp").forward(req, resp);
    }

    /**
     * 查询所有学院信息
     * 响应json给前端
     */
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();

        List<College> list = collegeService.getList();

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());//java8的时间需要加这个
        String jsonString = mapper.writeValueAsString(list);

        writer.println(jsonString);
        writer.flush();
    }

    /**
     * 添加学院
     */
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cname = req.getParameter("cname");
        String caddress = req.getParameter("caddress");
        String cphone = req.getParameter("cphone");

        String total = req.getParameter("total");
        String pages = req.getParameter("pages");


        Integer pageSize = new Page<>().getPageSize();

        Integer pages2 = Integer.valueOf(pages);
        if (Integer.parseInt(total) % pageSize == 0) {
            pages2 += 1;
        }

        HttpSession session = req.getSession();
        Admin admin = (Admin) session.getAttribute("auser");

        College college = new College(LocalDateTime.now(), admin.getAuser(), LocalDateTime.now(), admin.getAuser(), null, cname, caddress, cphone);
        int i = collegeService.addCollege(college);
        if (i > 0) {
            this.main(req, resp, String.valueOf(pages2));
        }
    }

    /**
     * 删除学院
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cid = req.getParameter("cid");
        int i = collegeService.deleteById(Integer.valueOf(cid));
        if (i > 0) {
            this.index(req, resp);
        }
    }

    /**
     * 批量删除所有选中学院
     * ❗️注意：接收数组记得加[]
     */
    protected void deleteSelect(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] ids = req.getParameterValues("ids[]");

        List<String> list = Arrays.asList(ids);
        List<Integer> integers = list.stream().map(Integer::valueOf).collect(Collectors.toList());

        int i = collegeService.deleteSelect(integers);
        if (i > 0) {
            this.index(req, resp);
        }
    }

    /**
     * 通过cid获取college对象
     */
    protected void getCollege(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String cid = req.getParameter("cid");

        College college = collegeService.getById(Integer.valueOf(cid));
        ObjectMapper mapper = new ObjectMapper();

        mapper.registerModule(new JavaTimeModule());//java8的时间需要加这个
        String jsonString = mapper.writeValueAsString(college);
        PrintWriter writer = resp.getWriter();
        writer.write(jsonString); //将json对象响应给前端
        writer.flush();
    }

    /**
     * 修改学院
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cid = req.getParameter("cid");
        String cname = req.getParameter("cname");
        String caddress = req.getParameter("caddress");
        String cphone = req.getParameter("cphone");


        String pn = req.getParameter("pn");


        HttpSession session = req.getSession();
        Admin admin = (Admin) session.getAttribute("auser");

        College college = new College(null, null, LocalDateTime.now(), admin.getAuser(), Integer.valueOf(cid), cname, caddress, cphone);

        int i = collegeService.updateById(college);
        if (i > 0) {
            this.main(req, resp, pn);
        }
    }

    /**
     * 查询所有学院数量
     */
    protected void count(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        long count = collegeService.count();
        PrintWriter writer = resp.getWriter();
        writer.println(count);
        writer.flush();
    }

    /**
     * 根据学院名查询学院信息
     */
    protected void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String cname = req.getParameter("cname");

        String pageNo = req.getParameter("pageNo");
        if (pageNo == null || Integer.parseInt(pageNo) <= 0) {
            pageNo = "1";
        }

        Page<College> page = collegeService.query(cname, Integer.valueOf(pageNo));

        req.setAttribute("cname", cname);
        req.setAttribute("page", page);
        req.getRequestDispatcher("/college_manage.jsp").forward(req, resp);
    }

    /**
     * 通过学院名判断该学院是否存在
     */
    protected void exit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());//java8的时间需要加这个
        //响应给前端的code,msg
        Map<String, Object> result = new HashMap<>();

        String cname = req.getParameter("cname");

        if (StringUtils.isBlank(cname)) {
            result.put("code", 0);
            result.put("msg", "学院名不能为空！");
            writer.println(mapper.writeValueAsString(result));
            return;
        }

        College college = collegeService.getByCname(cname);
        if (college != null) {
            result.put("code", 0);
            result.put("msg", "该学院已经存在！");
            writer.println(mapper.writeValueAsString(result));
            return;
        }
        result.put("code", 1);
        result.put("msg", "该学院不存在，可以新增");
        writer.println(mapper.writeValueAsString(result));
    }

    /**
     * 通过学院名判断该学院是否存在2
     */
    protected void exit2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());//java8的时间需要加这个
        //响应给前端的code,msg
        Map<String, Object> result = new HashMap<>();

        String cname = req.getParameter("cname");
        String pcname = req.getParameter("pcname");

        if (StringUtils.isBlank(cname)) {
            result.put("code", 0);
            result.put("msg", "学院名不能为空！");
            writer.println(mapper.writeValueAsString(result));
            return;
        }

        College college = collegeService.getByCname(cname);
        if (college != null && !college.getCname().equals(pcname)) {
            result.put("code", 0);
            result.put("msg", "该学院已经存在！");
            writer.println(mapper.writeValueAsString(result));
            return;
        }
        result.put("code", 1);
        result.put("msg", "该学院不存在，可以修改");
        writer.println(mapper.writeValueAsString(result));
    }
}
